﻿using System.ServiceModel.Description;
using ContainerHost.ServiceModel.Dispatcher;

namespace ContainerHost.ServiceModel.Description
{
    public class ContainerServiceBehavior : IServiceBehavior
    {
        public ContainerInstanceProvider InstanceProvider { get; set; }

        /// <summary>
        /// Initializes a new instance of the ContainerServiceBehavior class.
        /// </summary>
        public ContainerServiceBehavior(ContainerInstanceProvider instanceProvider)
        {
            InstanceProvider = instanceProvider;
        }

        /// <summary>
        /// Initializes a new instance of the ContainerServiceBehavior class.
        /// </summary>
        public ContainerServiceBehavior(IContainer container)
        {
            InstanceProvider = new ContainerInstanceProvider(container);
        }

        #region IServiceBehavior Members

        public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
            //do nothing
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {
            foreach (System.ServiceModel.Dispatcher.ChannelDispatcherBase cdb in serviceHostBase.ChannelDispatchers)
            {
                var cd = cdb as System.ServiceModel.Dispatcher.ChannelDispatcher;
                if (cd != null)
                {
                    foreach (System.ServiceModel.Dispatcher.EndpointDispatcher ed in cd.Endpoints)
                    {
                        InstanceProvider.ServiceType = serviceDescription.ServiceType;
                        ed.DispatchRuntime.InstanceProvider = InstanceProvider;
                    }
                }
            }
        }

        public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {
            //do nothing
        }

        #endregion
    }
}
